'use strict';

const Controller = require('egg').Controller;

class GenController extends Controller {

    /**
     * 设置代码配置项
     */
    async settingCodeColumns() {
        const { ctx } = this;
        const { tableName, columnsValue } = ctx.request.body;
        let opt_user = await ctx.service.auth.getColonyUserId();
        let retOpt = await ctx.service.generater.settingCodeColumns(tableName, columnsValue, opt_user);
        ctx.body = retOpt;
    }

    /**
     * 生成代码配置
     */
    async genCodeColumns() {
        const { ctx } = this;
        let columns = await ctx.service.generater.tableColumns(ctx.query.tablename);
        ctx.body = {
            code: 200,
            msg: "成功",
            data: columns
        };
    }

    /**
     * 生成代码
     */
    async genCode() {
        const { ctx, app, config } = this;
        const fs = require('fs');
        let path = require("path");//工具模块，处理文件路径的小工具
        const uuid = require('node-uuid');
        const { tablenames } = ctx.request.body;
        //生成文件夹
        let ufolder = await ctx.service.md5.cryptoPassFunc(uuid.v1() + new Date().getTime());
        let orgpath = config.baseDir + 'app/public/template/' + ufolder;
        console.log("orgpath====",orgpath);
        //生成代码
        for (var i = 0; i < tablenames.length; i++) {
            await ctx.service.generater.genCode(tablenames[i], orgpath);
        }
        //压缩文件
        let filePath = await app.utils.compress.zip(orgpath + "/代码生成", orgpath, "代码生成");
        this.ctx.attachment('代码生成.zip');
        this.ctx.set('Content-Type', 'application/octet-stream');
        const zip = await fs.createReadStream(filePath);
        //删除已经生产的文件
        setTimeout(()=>{
            //暂存30分钟，30分钟后自动删除
            ctx.service.fs.delPath(orgpath);
        },1000*60*30)
        this.ctx.body = zip;
    }

    /**
     * 查询数据库表列表
     */
    async tablelist() {
        const { ctx } = this;
        let data = await ctx.service.generater.tablelist(ctx.request.body);
        ctx.body = {
            code: 200,
            msg: "成功",
            data: data,
        };
    }
}

module.exports = GenController;